package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.mongodb.FileModel;
import com.ruoyi.common.core.mongodb.FileRepository;
import com.ruoyi.common.utils.MD5Util;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.service.FileService;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;



/**
 * @version v1.0
 * @ProjectName: ruoyi-vue-plus
 * @ClassName: FileServiceImpl
 * @Description: TODO(一句话描述该类的功能)
 * @Author: Yanghaha
 * @Date: 2021/5/14 11:31
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private FileRepository fileRepository;
    @Value("${server.address}")
    private  String serverAddress;

    @Value("${server.port}")
    private  String serverPort;
    @Override
    public FileModel saveFile(MultipartFile file) {
        FileModel returnFile = null;
        String path ="";
        try {
            String fileName = FileUploadUtils.uploadMongo(file);
            FileModel f = new FileModel(fileName, file.getContentType(), file.getSize(),
                    new Binary(file.getBytes()));
            f.setMd5(MD5Util.getMD5(file.getInputStream()));
            returnFile = fileRepository.save(f);
            path =  serverAddress + ":" + serverPort + "/files/view?id=" + returnFile.getId();
            returnFile.setPath(path);
            returnFile.setId(returnFile.getId());
            returnFile.setName(returnFile.getName());
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return returnFile;
    }

    @Override
    public void removeFile(String id) {
        fileRepository.deleteById(id);
    }

    @Override
    public Optional<FileModel> getFileById(String id) {
        return fileRepository.findById(id);
    }

    @Override
    public List<FileModel> listFilesByPage(int pageIndex, int pageSize) {
        Page<FileModel> page = null;
        List<FileModel> list = null;
        Sort sort = Sort.by(Sort.Direction.DESC,"uploadDate");
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        page = fileRepository.findAll(pageable);
        list = page.getContent();
        return list;
    }
}
